import {
  AfterViewChecked, Component, ContentChildren, ElementRef, Input, QueryList,
  ViewChild
} from '@angular/core';

import { ClassifyContainerComponent} from './classify-container'


@Component({
  selector: 'ion-classify-list',
  templateUrl: 'classify-list.html',
  inputs:['data']
})
export class ClassifyListComponent implements AfterViewChecked {
  data:Array<any>;
  _currentIndicator ;

  _flag= true;
  _indexes: any[]= []; //左侧导航
  _offsetTops: Array<number> = []; // 每个IndexSection 的offsetTop
  _navOffsetX: 0;
  _indicatorTime: any = null;
  _showModal = false;
  _ischeck=false;


  @Input() hasTop:boolean = false;
  @ViewChild('top') top: ElementRef;
  @ViewChild('scrollContent') scrollContent: ElementRef;
  @ContentChildren(ClassifyContainerComponent) _listOfIndexSection: QueryList<ClassifyContainerComponent>;

  constructor() {
    
  }

  ngAfterViewChecked(): void {
    if (this._flag && this._listOfIndexSection){
      this._listOfIndexSection.forEach((section) => {
        this._indexes.push(section.index);
        const offsetTop = section.getElementRef().nativeElement.offsetTop-25;
        this._offsetTops.push(offsetTop);
      });
      this._flag = false;

      if(this.hasTop) {
        this._indexes.unshift('#');
        this._offsetTops.unshift(0);
      }
      this._currentIndicator=this._indexes[0];
    }
  }

  onScroll(e:any) {
    if(this._ischeck)return;
    e.preventDefault();
    const scrollTopOffsetTop = this.scrollContent.nativeElement.scrollTop;
    this._offsetTops.forEach((v, i) => {
      if (scrollTopOffsetTop >= v){
        this._currentIndicator = this._indexes[i];
      }
    });
  }


  select(item){
    this._ischeck=true;
    this._currentIndicator=item.index;
    this.scrollList();
  }

  scrollList(){

    const index = this._indexes.indexOf(this._currentIndicator);
    this.scrollContent.nativeElement.scrollTop = this._offsetTops[index]+15;
    setTimeout(()=>{
      this._ischeck=false;
    },500);
    
  }

}
